<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTTP 请求工具</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f4f4f4;
            padding: 20px;
        }
        .container {
            max-width: 900px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            margin-bottom: 20px;
            color: #2c3e50;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            font-family: monospace;
        }
        textarea {
            min-height: 150px;
        }
        button {
            display: block;
            width: 100%;
            padding: 12px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
            margin-bottom: 15px;
        }
        button:hover {
            background-color: #2980b9;
        }
        button:disabled {
            background-color: #95a5a6;
            cursor: not-allowed;
        }
        .status {
            margin-top: 15px;
            padding: 10px;
            border-radius: 4px;
            display: none;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        .flex-row {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }
        .flex-row select {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            min-width: 120px;
        }
        .flex-row input {
            flex: 1;
        }
        .response-container {
            margin-top: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
            overflow: hidden;
        }
        .response-header {
            background-color: #f8f9fa;
            padding: 10px;
            border-bottom: 1px solid #ddd;
            font-weight: bold;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .response-body {
            padding: 10px;
            max-height: 400px;
            overflow-y: auto;
            background-color: #f8f9fa;
            font-family: monospace;
        }
        .json-viewer {
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        .copy-btn {
            width: auto;
            padding: 5px 10px;
            font-size: 14px;
        }
        .tabs {
            display: flex;
            border-bottom: 1px solid #ddd;
            margin-bottom: 15px;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            background-color: #f8f9fa;
            border: 1px solid #ddd;
            border-bottom: none;
            margin-right: 5px;
            border-radius: 4px 4px 0 0;
        }
        .tab.active {
            background-color: white;
            border-bottom: 1px solid white;
            margin-bottom: -1px;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        .history-item {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .history-item:hover {
            background-color: #f8f9fa;
        }
        .history-item-header {
            font-weight: bold;
            margin-bottom: 5px;
        }
        .history-item-method {
            display: inline-block;
            padding: 2px 6px;
            background-color: #3498db;
            color: white;
            border-radius: 3px;
            font-size: 12px;
            margin-right: 8px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>HTTP 请求工具</h1>
        
        <div class="tabs">
            <div class="tab active" data-tab="request">发送请求</div>
            <div class="tab" data-tab="history">历史记录</div>
        </div>
        
        <div id="request-tab" class="tab-content active">
            <div class="flex-row">
                <select id="method">
                    <option value="GET">GET</option>
                    <option value="POST">POST</option>
                    <option value="PUT">PUT</option>
                    <option value="DELETE">DELETE</option>
                    <option value="PATCH">PATCH</option>
                    <option value="HEAD">HEAD</option>
                    <option value="OPTIONS">OPTIONS</option>
                </select>
                <input type="text" id="path" placeholder="输入路径 (如: /api/sensor)" value="/api/sensor">
            </div>
            
            <div class="form-group">
                <label for="payload">负载 (JSON):</label>
                <textarea id="payload" placeholder="输入JSON负载...">{"cmd": "MPU6050"}</textarea>
            </div>
            
            <button id="send-btn">发送请求</button>
        </div>
        
        <div id="history-tab" class="tab-content">
            <div id="history-list">
                <p>暂无历史记录</p>
            </div>
        </div>
        
        <div class="response-container">
            <div class="response-header">
                <span>响应结果</span>
                <button id="copy-btn" class="copy-btn">复制</button>
            </div>
            <div class="response-body">
                <pre class="json-viewer" id="response"></pre>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const methodSelect = document.getElementById('method');
            const pathInput = document.getElementById('path');
            const payloadTextarea = document.getElementById('payload');
            const sendButton = document.getElementById('send-btn');
            const responseDiv = document.getElementById('response');
            const copyButton = document.getElementById('copy-btn');
            const tabs = document.querySelectorAll('.tab');
            const tabContents = document.querySelectorAll('.tab-content');
            const historyList = document.getElementById('history-list');
            
            // 历史记录数组
            let requestHistory = [];
            const MAX_HISTORY = 10;
            
            // 加载历史记录
            function loadHistory() {
                const savedHistory = localStorage.getItem('httpRequestHistory');
                if (savedHistory) {
                    requestHistory = JSON.parse(savedHistory);
                    updateHistoryUI();
                }
            }
            
            // 保存历史记录
            function saveHistory() {
                localStorage.setItem('httpRequestHistory', JSON.stringify(requestHistory));
                updateHistoryUI();
            }
            
            // 更新历史记录UI
            function updateHistoryUI() {
                if (requestHistory.length === 0) {
                    historyList.innerHTML = '<p>暂无历史记录</p>';
                    return;
                }
                
                historyList.innerHTML = '';
                requestHistory.forEach((item, index) => {
                    const historyItem = document.createElement('div');
                    historyItem.className = 'history-item';
                    
                    const header = document.createElement('div');
                    header.className = 'history-item-header';
                    header.innerHTML = `
                        <span class="history-item-method">${item.method}</span>
                        ${item.path}
                    `;
                    
                    const timestamp = document.createElement('div');
                    timestamp.style.fontSize = '12px';
                    timestamp.style.color = '#666';
                    timestamp.textContent = new Date(item.timestamp).toLocaleString();
                    
                    historyItem.appendChild(header);
                    historyItem.appendChild(timestamp);
                    
                    historyItem.addEventListener('click', () => {
                        methodSelect.value = item.method;
                        pathInput.value = item.path;
                        payloadTextarea.value = item.payload;
                        
                        // 切换到请求标签
                        document.querySelector('.tab.active').classList.remove('active');
                        document.querySelector('.tab-content.active').classList.remove('active');
                        document.querySelector('.tab[data-tab="request"]').classList.add('active');
                        document.getElementById('request-tab').classList.add('active');
                    });
                    
                    historyList.appendChild(historyItem);
                });
            }
            
            // 添加到历史记录
            function addToHistory(method, path, payload) {
                const historyItem = {
                    method,
                    path,
                    payload,
                    timestamp: Date.now()
                };
                
                // 添加到开头
                requestHistory.unshift(historyItem);
                
                // 限制历史记录数量
                if (requestHistory.length > MAX_HISTORY) {
                    requestHistory = requestHistory.slice(0, MAX_HISTORY);
                }
                
                saveHistory();
            }
            
            // 格式化JSON显示
            function formatJson(jsonStr) {
                try {
                    const parsed = JSON.parse(jsonStr);
                    return JSON.stringify(parsed, null, 2);
                } catch (e) {
                    return jsonStr; // 如果不是有效的JSON，返回原始字符串
                }
            }
            
            // 发送请求
            async function sendRequest() {
                const method = methodSelect.value;
                const path = pathInput.value.trim();
                const payload = payloadTextarea.value.trim();
                
                if (!path) {
                    responseDiv.textContent = '错误: 请输入路径';
                    return;
                }
                
                // 显示加载状态
                sendButton.textContent = '发送中...';
                sendButton.disabled = true;
                responseDiv.textContent = '正在发送请求...';
                
                try {
                    // 准备请求选项
                    const options = {
                        method: method,
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    };
                    
                    // 如果不是GET/HEAD请求且有负载，添加请求体
                    if (method !== 'GET' && method !== 'HEAD' && payload) {
                        // 验证JSON格式
                        try {
                            JSON.parse(payload);
                            options.body = payload;
                        } catch (e) {
                            throw new Error('无效的JSON格式');
                        }
                    }
                    
                    // 发送请求
                    const response = await fetch(path, options);
                    
                    // 先读取为文本，再尝试解析JSON
                    const textData = await response.text();
                    try {
                        const jsonData = JSON.parse(textData);
                        responseDiv.textContent = formatJson(JSON.stringify(jsonData));
                    } catch (e) {
                        responseDiv.textContent = textData;
                    }
                    
                    // 添加到历史记录
                    addToHistory(method, path, payload);
                    
                } catch (error) {
                    responseDiv.textContent = `错误: ${error.message}`;
                } finally {
                    sendButton.textContent = '发送请求';
                    sendButton.disabled = false;
                }
            }
            
            // 复制响应
            function copyResponse() {
                const text = responseDiv.textContent;
                navigator.clipboard.writeText(text).then(() => {
                    const originalText = copyButton.textContent;
                    copyButton.textContent = '已复制!';
                    setTimeout(() => {
                        copyButton.textContent = originalText;
                    }, 2000);
                }).catch(err => {
                    console.error('复制失败:', err);
                });
            }
            
            // 切换标签
            tabs.forEach(tab => {
                tab.addEventListener('click', () => {
                    const tabId = tab.getAttribute('data-tab');
                    
                    // 移除所有活跃状态
                    tabs.forEach(t => t.classList.remove('active'));
                    tabContents.forEach(content => content.classList.remove('active'));
                    
                    // 添加当前活跃状态
                    tab.classList.add('active');
                    document.getElementById(tabId + '-tab').classList.add('active');
                });
            });
            
            // 事件监听
            sendButton.addEventListener('click', sendRequest);
            copyButton.addEventListener('click', copyResponse);
            
            // 初始化
            loadHistory();
        });
    </script>
</body>
</html>